package server

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"smart-weekly-report/config"
	"time"
)

// 飞书服务结构
type FeishuService struct {
	WebhookURL string
	FeishuKey  string
}

// 飞书响应结构
type FeishuResponse struct {
	Code    int    `json:"code"`
	Message string `json:"msg"` // 注意：飞书API使用"msg"字段表示消息
	Data    any    `json:"data"`
}

func NewFeishuService(webhookURL string, FeishuKey string) *FeishuService {
	return &FeishuService{WebhookURL: webhookURL, FeishuKey: FeishuKey}
}

// 发送周报到飞书群
func (fs *FeishuService) SendWeeklyReport(report *WeeklyReport) error {
	message := map[string]interface{}{
		"msg_type": "text",
	}
	message["content"] = fmt.Sprintf("📊 智能周报生成完成\n\n周数：第%d周\n生成时间：%s\n\n%s",
		report.Week,
		report.GeneratedAt.Format("2006-01-02 15:04:05"),
		report.Content,
	)
	timestamp := time.Now().Unix()
	sign, err := fs.generateSign(fs.FeishuKey, timestamp)
	if sign != "" {
		message["sign"] = sign
		message["timestamp"] = fmt.Sprintf("%d", timestamp)
	}

	jsonData, err := json.Marshal(message)
	if err != nil {
		return err
	}

	resp, err := http.Post(fs.WebhookURL, "application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		return fmt.Errorf("飞书消息发送失败，状态码：%d", resp.StatusCode)
	}

	// 更新发送状态
	report.Sent = true
	config.Db.Save(report)

	return nil
}

// 发送格式化消息卡片
func (fs *FeishuService) SendFormattedCard(report *WeeklyReport) error {
	// 创建正确的消息结构 - msg_type 和 card 应该在同一层级
	message := map[string]interface{}{
		"msg_type": "interactive",
		"card": map[string]interface{}{
			"config": map[string]interface{}{
				"wide_screen_mode": true,
			},
			"header": map[string]interface{}{
				"title": map[string]interface{}{
					"tag":     "plain_text",
					"content": fmt.Sprintf("📊 第%d周智能周报", report.Week),
				},
				"color": "0080FF", // 添加标准颜色值
			},
			// 将内容移到正确的 sections 字段中
			"elements": []map[string]interface{}{ // 使用 elements 替代原来的错误嵌套
				{
					"tag": "div",
					"text": map[string]interface{}{
						"tag":     "lark_md",
						"content": report.Content,
					},
				},
				{
					"tag": "note",
					"elements": []map[string]interface{}{
						{
							"tag":     "plain_text",
							"content": fmt.Sprintf("生成时间：%s", report.GeneratedAt.Format("2006-01-02 15:04:05")),
						},
					},
				},
			},
		},
	}
	timestamp := time.Now().Unix()
	sign, err := fs.generateSign(fs.FeishuKey, timestamp)
	if sign != "" {
		message["sign"] = sign
		message["timestamp"] = fmt.Sprintf("%d", timestamp)
	}
	jsonData, err := json.Marshal(message)
	if err != nil {
		return err
	}
	fmt.Println(string(jsonData))
	resp, err := http.Post(fs.WebhookURL, "application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	// 解析响应结果
	responseBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("读取卡片响应失败: %w", err)
	}

	// 解析JSON响应
	var feishuResp FeishuResponse
	if err := json.Unmarshal(responseBody, &feishuResp); err != nil {
		// 如果无法解析JSON，直接返回原始响应内容
		return fmt.Errorf("解析卡片响应失败: %w, 原始响应: %s", err, string(responseBody))
	}

	// 检查响应状态
	if resp.StatusCode != 200 || feishuResp.Code != 0 {
		return fmt.Errorf("飞书卡片发送失败，状态码：%d，错误码：%d，错误消息：%s",
			resp.StatusCode, feishuResp.Code, feishuResp.Message)
	}
	return nil
}

// 生成飞书签名
func (r *FeishuService) generateSign(secret string, timestamp int64) (string, error) {
	if secret == "" {
		return "", fmt.Errorf("secret is empty")
	}
	//timestamp + key 做sha256, 再进行base64 encode
	stringToSign := fmt.Sprintf("%v", timestamp) + "\n" + secret
	var data []byte
	h := hmac.New(sha256.New, []byte(stringToSign))
	_, err := h.Write(data)
	if err != nil {
		return "", err
	}
	signature := base64.StdEncoding.EncodeToString(h.Sum(nil))
	return signature, nil
}
